document.addEventListener('DOMContentLoaded', function() {
    // 初始化轮播图
    class Carousel {
        constructor() {
            this.slideIndex = 1;
            this.slides = document.getElementsByClassName("mySlides");
            this.dotsContainer = document.querySelector(".dot-container");
            
            this.initDots();
            this.showSlides(this.slideIndex);
            this.addEventListeners();
            this.autoPlay();
        }

        initDots() {
            // 创建指示点
            for (let i = 0; i < this.slides.length; i++) {
                const dot = document.createElement("span");
                dot.className = "dot";
                dot.addEventListener("click", () => this.currentSlide(i + 1));
                this.dotsContainer.appendChild(dot);
            }
        }

        showSlides(n) {
            const dots = document.getElementsByClassName("dot");
            
            // 处理边界
            if (n > this.slides.length) this.slideIndex = 1;
            if (n < 1) this.slideIndex = this.slides.length;

            // 隐藏所有幻灯片
            Array.from(this.slides).forEach(slide => {
                slide.style.display = "none";
            });

            // 更新指示点
            Array.from(dots).forEach(dot => {
                dot.className = dot.className.replace(" active", "");
            });

            // 显示当前幻灯片
            this.slides[this.slideIndex - 1].style.display = "block";
            dots[this.slideIndex - 1].className += " active";
        }

        addEventListeners() {
            // 导航按钮事件
            document.querySelector(".prev").addEventListener("click", () => this.plusSlides(-1));
            document.querySelector(".next").addEventListener("click", () => this.plusSlides(1));
        }

        plusSlides(n) {
            this.showSlides(this.slideIndex += n);
        }

        currentSlide(n) {
            this.showSlides(this.slideIndex = n);
        }

        autoPlay() {
            setInterval(() => {
                this.plusSlides(1);
            }, 5000);
        }
    }

    // 创建轮播实例
    new Carousel();
});
